//
//  DeliveryDetailsVC.m
//  ProjectforHDX
//
//  Created by HDX on 16/8/8.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "DeliveryDetailsVC.h"
#import "DeliveryHV.h"
#import "DeliveryFV.h"
#import "DeliveryModel.h"
#import "PartsItemV.h"
#import "DeliveryPartsTC.h"
#import "DeliveryPartsInfoTC.h"
#import "MHScanViewController.h"
@interface DeliveryDetailsVC ()<UITableViewDelegate,UITableViewDataSource,PXAlertViewDelegate>
{
    //是否隐藏
    BOOL  open;
    
}

/**
 *  用户数据模型
 */
@property (nonatomic, strong) THUserInfoModel *userModel;

//推荐打包件
@property (nonatomic, strong) NSMutableArray *tableArray;

/**
 *  已经打包件
 */
@property (nonatomic, strong) NSMutableArray *tableParts;
/**
 *  正要打包件
 */
@property (nonatomic, strong) NSMutableArray *selectParts;

@property (nonatomic, strong) UITableView *tableView;

/**
 *  服务器返回的data总数据
 */
@property (nonatomic, strong) NSMutableDictionary *dataDict;

/**
 *  订单信息
 */
@property (nonatomic, strong) NSMutableDictionary *orderInfoDict;

/**
 *  权限字典
 */
@property (nonatomic, strong) NSMutableDictionary *permissionsDict;

/**
 *  物流信息
 */
@property (nonatomic, strong) NSMutableDictionary *logisticsInfoDict;


/**
 *  需要发送的板件
 */
@property (nonatomic, strong) NSMutableArray *recommendedArray;

/**
 *  物流公司数组
 */
@property (nonatomic, strong) NSMutableArray *logisCompanyArray;



/**
 *  当前的包装规格
 */
@property(nonatomic,strong) NSMutableDictionary *currentPackingSpecificationDict;

/**
 *  当前包裹信息
 */
@property(nonatomic,strong) NSMutableDictionary *currentPackingDict;

/**
 批次数组
 */
@property(nonatomic, strong) NSMutableArray *packageIndexArray;



@end

@implementation DeliveryDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.labnav.textColor = [UIColor whiteColor];
    self.labnav.text =[THMangerTool language:@"delivery.title"];// [UtilCheck language:@"setting.consignee"];
    self.mBackColor = [UtilCheck hexStringToColor:@"f6f7fb" alpha:1];
    
    self.userModel=[THMangerTool getAccountInfo];
    open=YES;
    
    self.tableArray=[[NSMutableArray alloc] initWithCapacity:0];
    self.tableParts=[[NSMutableArray alloc] initWithCapacity:0];
    self.selectParts=[[NSMutableArray alloc] initWithCapacity:0];
    self.packageIndexArray=[[NSMutableArray alloc] initWithCapacity:0];
    [self  requestDetails];
 
    
}

#pragma mark 网络请求

//打包发货接口
- (void)submitPackageDelivery{
    
    [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];

    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:self.orderCode forKey:@"orderCode"];
    [dict setValue:self.logisticsInfoDict forKey:@"logisticsInfo"];
    
    
    NSMutableArray *packagesArray = [[NSMutableArray alloc]init];
    for (int j = 0 ; j < self.packageIndexArray.count ; j++) {
        NSMutableArray *tempArray = [THMangerTool deepCopy: [self.packageIndexArray[j] mutableCopy]];
        
        for ( int i = 0 ; i < tempArray.count ; i ++) {
            NSMutableDictionary *tempDict = [THMangerTool deepCopy:[tempArray[i] mutableCopy]];
            [tempDict setValue:[NSString stringWithFormat:@"%d",j] forKey:@"batch"];
            [packagesArray addObject:tempDict];
        }
    }
    
    [dict setValue:packagesArray forKey:@"packages"];
    [AFHttpTool postJsonDatawithUrl:@"packageDelivery" parameters:dict success:^(id responseObject) {
        [[BDHUD sharedManager] dismissHUD];

        
        if ([[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] == 1) {
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            
            int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index -2)] animated:YES];
            

        }else {
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
        }
        
    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];

        
        
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];

}



//获取物流公司
- (void)getLogisCompanyData{
    [AFHttpTool postJsonDatawithUrl:@"getLogisticsCompany" parameters:nil success:^(id responseObject) {
        
        if ([[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] == 1) {
            self.logisCompanyArray = [[NSMutableArray alloc]initWithArray:[responseObject objectForKey:@"data"]];
            
            NSMutableArray *actionArray = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in self.logisCompanyArray) {
                [actionArray addObject:dic[@"name"]];
            }
            PXAlertView *AlertView = [[PXAlertView alloc]initAlertWithTitle:[UtilCheck language:@"order.logistics.company"] message:nil cancelTitle:nil otherTitle:nil contentView:nil completion:nil tableview:actionArray];
            AlertView.delegate = self;
            AlertView.mark = 1000;
            [AlertView show];
        }else {
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];

}
//根据二维码获取扫码后的信息
- (void)getPartInfoWith:(NSString *)str{
    NSDictionary *post=[[NSDictionary alloc] initWithObjectsAndKeys:str,@"plateSN",@0,@"plateCode",@0,@"containerCode", nil];

    [AFHttpTool postJsonDatawithUrl:@"getPartInfo1" parameters:[post mutableCopy] success:^(id responseObject) {
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:[responseObject objectForKey:@"data"]];
                [self isCanAddDict:dict];
            }
            else{
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                else{
                    [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                }
            }
            
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
    }];

}
//系统自动推荐客服发货和仓管发货清单共用接口
- (void)requestDetails {
    [[BDHUD sharedManager] showBDHUD:self.view title:@"HUD.title"];
    sleep(0.5);
    [[BDHUD sharedManager] dismissHUD];
 
    NSDictionary *post=[[NSDictionary alloc] initWithObjectsAndKeys:self.orderCode,@"orderCode", nil];
 
    [AFHttpTool postJsonDatawithUrl:@"recommendShipping" parameters:[post mutableCopy] success:^(id responseObject) {
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *data=[responseObject objectForKey:@"data"];
              
                self.dataDict = [[NSMutableDictionary alloc]initWithDictionary:data];
                [self initView];
            }
            else{
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                else{
                    [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                }
            }
 
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
          
        }
    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
 
    }];
    
    
    
}
-(void)initView{
    
    
    self.orderInfoDict = [[NSMutableDictionary alloc]initWithDictionary:[self.dataDict objectForKey:@"orderInfo"]];
    self.permissionsDict = [[NSMutableDictionary alloc]initWithDictionary:[self.dataDict objectForKey:@"permissions"]];
    self.logisticsInfoDict = @{@"code":@"",
                               @"com":@"",
                               @"courierID":@""
                               }.mutableCopy,
    self.recommendedArray = [[NSMutableArray alloc]initWithArray:[self.dataDict objectForKey:@"recommended"]];

    self.currentPackingDict = [[NSMutableDictionary alloc]init];
    
    self.tableArray = [[NSMutableArray alloc]initWithArray:self.recommendedArray];
    

    
    
    self.selectParts= [[NSMutableArray alloc]init];

    
    {
        self.tableView = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height-60) style:UITableViewStyleGrouped];
            
            [tableView setBackgroundColor:[UtilCheck hexStringToColor:@"ffffff" alpha:1]];
            tableView.showsVerticalScrollIndicator=YES;
            tableView.showsHorizontalScrollIndicator=NO;
            tableView.bounces=NO;
            tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
            tableView.delegate=self;
            tableView.dataSource=self;
            tableView;
        });
        
        if(IOS7){
            [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
        }
        [self.view addSubview:self.tableView];
        
    }
    self.tableView.tableHeaderView=[self createHeaderView];
 
    [self createBottomView];
}

/**
 *  订单信息视图
 */
-(UIView*)createHeaderView{
    
    DeliveryHV *headerView=[[DeliveryHV alloc] initDHVWithFram:CGRectMake(0, 0, self.tableView.width, 0) OrderInfo:self.orderInfoDict onClick:^{
        
    }];
    return headerView;
}
/**
 *  创建物流信息视图
 */
-(UIView*)createFooterView{
    DeliveryFV *footerView=[[DeliveryFV alloc] initDHVWithFram:CGRectMake(0, 0, self.tableView.width, 90) logistics:self.logisticsInfoDict onClick:^(NSDictionary *dict) {
        
        self.logisticsInfoDict = [dict mutableCopy];
        [self.tableView reloadData];
        
    }];
    return footerView;
}
/**
 *  创建底部按钮
 */
-(void)createBottomView{
    
    UIView *btnView=[[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 60, self.view.width, 60)];
    //线
    [btnView addSoldLine:1 soldcolor:[UtilCheck hexStringToColor:@"e1e1df" alpha:1] pointA:CGPointMake(0, 0) pointB:CGPointMake(btnView.width,0)];
    [self.view addSubview:btnView];
 
  NSArray *arr= @[@"1",@"2",@"3",@"4"];
    NSInteger count=4;
    CGFloat btnwidth=65;
        CGFloat btnheight=30;
    for(int i=0;i<count;i++){
        
        NSString *title=[THMangerTool operationDeliver:[arr objectAtIndex:count - 1 - i]];
        RZCustomButtom *submit=[[RZCustomButtom alloc] init];
        [submit setFrame:CGRectMake(self.view.width  - (i+ 1)*(10 +btnwidth) ,(btnView.height-btnheight)/2.f,btnwidth,btnheight)];
        [submit setTitle:title forState:UIControlStateNormal];//确认
        submit.tag=100+[[arr objectAtIndex:count - 1 - i] intValue];
        [submit addRadius:1 borderwidth:1 bordercolor:[UtilCheck hexStringToColor:@"9ea7ad" alpha:1]];
        [submit setTitleColor:[UtilCheck hexStringToColor:@"9ea7ad" alpha:1]  forState:UIControlStateNormal ];
        [submit.titleLabel setFont:CustomFont(12)];
        [btnView addSubview:submit];
        [submit addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside ];
 
        if(i==0){
            [submit setBackgroundColor:[Toolobject getColorByRGB:26 green:86 blue:188 alpha:1]];
            [submit addRadius:1 borderwidth:1 bordercolor:[Toolobject getColorByRGB:26 green:86 blue:188 alpha:1]];
           [submit setTitleColor:[UtilCheck hexStringToColor:@"ffffff" alpha:1]  forState:UIControlStateNormal ];
        }
    }
    
    
}

#pragma mark 底部按钮点击
/**
 *  按钮点击
 *sender.tag 1手动添加 2手动扫码  3打包 4发货
 *  @param sender
 */
-(void)btnClick:(RZCustomButtom*)sender{

    NSLog(@"点击了第%ld个按钮",sender.tag - 100);
    switch (sender.tag-100) {
        case 1:
        {
            [[BDHUD sharedManager] showViewToView:self.view ContentType:0 headImage:nil headTitle:[THMangerTool language:@"show.add"] headColor:nil text: @[@{@"key":@"partsSN",@"placeholder":[NSString stringWithFormat:@"%@ 必填",[THMangerTool language:@"setting.plateSerial"]],@"type":@"0"},@{@"key":@"partsCode",@"placeholder":[THMangerTool language:@"setting.plateNO"],@"type":@"0"},@{@"key":@"partsVersion",@"placeholder":[THMangerTool language:@"setting.plateCode"],@"type":@"0"},@{@"key":@"partsName",@"placeholder":[THMangerTool language:@"setting.plateName"],@"type":@"0"}] bottons:@[[THMangerTool language:@"show.add"],[THMangerTool language:@"show.cancel"]] click:^(NSInteger index, id responseObject) {
                
                    if (index == 0) {
                        NSLog(@"点击了手动添加");
                        NSLog(@"返回值是%@",responseObject);
                        
                        NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:responseObject];
                        
                        if (!dict ||  dict.count <= 0) {
                            [Toolobject showTextWithMessage:@"请输入信息"];
                            return ;
                        }
                        
                        [self isCanAddDict:dict];

                    }
                
            }];

            
        }
            break;
        case 2:
        {
            MHScanViewController *scanVC = [[MHScanViewController alloc] init];
            scanVC.isdismiss=YES;
            scanVC.rebackData = ^(NSString *retStr) {
#pragma mark 扫码获取板件信息
                [self getPartInfoWith:retStr];
            };
            CustomNavigationController *vc = [[CustomNavigationController alloc ]initWithRootViewController:scanVC];
            
            [self presentViewController:vc animated:YES completion:^{
                
            }];
            
        }
            break;
        case 3://获取包装规格
        {
            
            if (self.selectParts.count < 1) {
                [Toolobject showTextWithMessage:@"请先添加板件"];
                break;
            }
            [[BDHUD sharedManager] showViewToView:self.view ContentType:0 headImage:nil headTitle:[THMangerTool language:@"show.pack"] headColor:nil text: @[@{@"key":@"name",@"placeholder":[THMangerTool language:@"show.packMsg"],@"type":@"1"}] bottons:@[[THMangerTool language:@"show.pack"],[THMangerTool language:@"show.cancel"]] click:^(NSInteger index, id responseObject) {
                
                if (index == 0) {
                    self.currentPackingSpecificationDict = [responseObject mutableCopy];
                    [self.currentPackingDict setObject:self.currentPackingSpecificationDict forKey:@"specificationInfo"];
                    [self.currentPackingDict setObject:[THMangerTool deepCopy: self.selectParts] forKey:@"parts"];
                    
                    
                    if (self.packageIndexArray.count <= 0) {
                        NSMutableArray *firstArray = [[NSMutableArray alloc]init];
                        [self.packageIndexArray addObject:firstArray];
                    }
                    
#pragma mark 弹出一个框，选择批次
                    
                    NSMutableArray *array = [[NSMutableArray alloc]init];
                    int count = (int)self.packageIndexArray.count;
                    for (int i = 0 ; i < count ; i ++ ) {
                        [array addObject:[NSString stringWithFormat:@"第%d批次",i+1]];
                    }
                    PXAlertView *alert = [[PXAlertView alloc] initAlertWithTitle:@"请选择批次" message:nil cancelTitle:nil otherTitle:nil contentView:nil completion:nil tableview:array];
                    alert.delegate = self;
                    alert.mark = 1002;
                    [alert show];
                    
                }
                
            }];
        }
            break;
        case 4://发货
        {
            if (self.packageIndexArray.count < 1) {
                [Toolobject showTextWithMessage:@"请先打包"];
                return;
            }
            [self submitPackageDelivery];
        }
            break;
        case 5:
        {
            
        }
            break;
        case 6:
        {
            
        }
            break;
        case 7:
        {
            
        }
            break;
            
        default:
            break;
    }
}
#pragma mark TableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
    return 40;
    }
    else{
        return 110 * self.packageIndexArray.count + 50;;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section==0){
        if ([[self.orderInfoDict objectForKey:@"type"] integerValue] == 1) {
            return 0.1;
            
        }else{
            return  90;
            
        }
    }
    else{
        return 0.1;
    }
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(section==0){
        if ([[self.orderInfoDict objectForKey:@"type"] integerValue] == 1) {
            return nil;
  
        }else{
            return  [self createFooterView];

        }
    }
    else{
        return nil;
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 40)];
    [headerView setBackgroundColor:[UtilCheck getRZColor:244 green:248 blue:251 alpha:1]];
    if(section==0){
    RZCustomLable *labName=[[RZCustomLable alloc] init];
    [labName setFont:CustomFont(14)];
    [labName setTextColor:[UtilCheck hexStringToColor:@"9d9fa1" alpha:1] ];
    [headerView addSubview:labName];
    
    [labName setFrame:CGRectMake(10, 0, 120, headerView.height)];
    labName.text=[THMangerTool language:@"delivery.delTitle"];
    labName.numberOfLines=1;
    [labName sizeToFit];
    labName.left=10;
    labName.height=headerView.height;
    
        RZCustomButtom *btnOpen=[[RZCustomButtom alloc] init];
        [btnOpen setImage:BDFILEIMAGENAEM(@"wareHouseDeliver/deliverInfoClose") forState:UIControlStateNormal];
        [btnOpen setImage:BDFILEIMAGENAEM(@"wareHouseDeliver/deliverInfoExt") forState:UIControlStateSelected];
        [btnOpen addTarget:self action:@selector(btnOpen:) forControlEvents:UIControlEventTouchUpInside];
        [btnOpen setFrame:CGRectMake(labName.right+5, (headerView.height-20)/2.f, 20, 20)];
        btnOpen.selected=open;
        [headerView addSubview:btnOpen];
        

        
    //板件信息
    CustomLabel *labUrgent=[[CustomLabel alloc] initWithFrame:CGRectMake(headerView.right, 0, headerView.width, 300)];
    [labUrgent setFont:CustomFont(14)];
        NSString *string=[NSString stringWithFormat:@"<font color='blue'>%ld</font>",(long)self.tableArray.count];
    NSString *htmlString= [NSString stringWithFormat:[THMangerTool language:@"delivery.parts"],string];
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    
    labUrgent.attributedText=attrStr;
    labUrgent.numberOfLines=1;
    
    CGSize size=[labUrgent  preferredSizeWithMaxWidth:headerView.width];
    labUrgent.width=size.width;
    labUrgent.left=headerView.width-labUrgent.width-10;
    labUrgent.height=headerView.height;
    [headerView addSubview:labUrgent];
    }
    else{
        headerView.height=110 * self.packageIndexArray.count + 50;
        UIView *partsView=[[UIView alloc] initWithFrame:CGRectMake(0, 10, headerView.width, 110 * self.packageIndexArray.count )];
        [partsView setBackgroundColor:[UIColor whiteColor]];
        
        for (int j = 0 ; j < self.packageIndexArray.count; j ++ ) {
            {
                
                UIView *cellView = [[UIView alloc]initWithFrame:CGRectMake(0, 110 * j, partsView.width  , 110)];
                            
                if (j == 0) {
                    UIView *partHeadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, partsView.width , 40)];
                    [partHeadView setBackgroundColor:[UtilCheck hexStringToColor:LineColor alpha:1]];

                    UIButton *addBtn = [[UIButton alloc]initWithFrame:CGRectMake(partHeadView.width - 70, 10, 60, 20)];

                    [addBtn setTitle:@"添加批次" forState:UIControlStateNormal];
                    [addBtn setTitle:@"添加批次" forState:UIControlStateHighlighted];
                 
                    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
                    [addBtn setBackgroundColor:SYSTEM_COLOR];
                    
                    addBtn.titleLabel.font = [UIFont systemFontOfSize:13];
                    addBtn.tag = 2000;
                    [addBtn addTarget:self action:@selector(touchAddBtn:) forControlEvents:UIControlEventTouchUpInside];
                    [partHeadView addSubview:addBtn];
                    
                    
                    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40)];
                    label.text = [NSString stringWithFormat:@"批次、打包"];
                    label.textColor = [UIColor blueColor];
                    label.font = [UIFont systemFontOfSize:13];
                    [partHeadView addSubview:label];
                    
                    [cellView addSubview:partHeadView];

                }
                
                
                //批次标题  减号
                UIButton *indexBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, 60, 70)];
                [indexBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                [indexBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateHighlighted];
                indexBtn.titleLabel.numberOfLines = 0;
                indexBtn.titleLabel.font = [UIFont systemFontOfSize:13];
                [indexBtn setTitle:[NSString stringWithFormat:@"批次%d:",j+1] forState:UIControlStateNormal];
                [indexBtn setTitle:[NSString stringWithFormat:@"批次%d:",j+1] forState:UIControlStateHighlighted];
                
                if (j != 0 && j == self.packageIndexArray.count - 1) {
                    [indexBtn setTitle:[NSString stringWithFormat:@"批次%d:\n\n  ➖",j+1] forState:UIControlStateNormal];
                    [indexBtn setTitle:[NSString stringWithFormat:@"批次%d:\n\n  ➖",j+1] forState:UIControlStateHighlighted];
                    indexBtn.tag = 2000 + j;
                    [indexBtn addTarget:self action:@selector(touchAddBtn:) forControlEvents:UIControlEventTouchUpInside];
                }
                [cellView addSubview:indexBtn];

                
                UIScrollView *partScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(70, 40, partsView.width-80, 80)];
                
                NSMutableArray *indexArray = [[NSMutableArray alloc]initWithArray:self.packageIndexArray[j]];
                NSInteger count = indexArray.count;
                
                
                for(int i=0;i<count;i++){
                    NSMutableDictionary *tempDict = [[indexArray objectAtIndex:i] mutableCopy];
                    NSMutableArray *tempArr = [[NSMutableArray alloc]initWithArray:[tempDict objectForKey:@"parts"]];
                    PartsItemV *itemView = [[PartsItemV alloc] initDHVWithFram:CGRectMake(i*70, 0, 60, 80) ordinal:i+1  Data:tempArr  onClick:^(BOOL isSee)  {
                        if(isSee){
                        }
                        else{
                            NSLog(@"itemview的====j=%d ====i===%d",j ,i);
                            NSMutableArray *tempArray = [[NSMutableArray alloc]initWithArray:self.packageIndexArray[j]];
                            [tempArray removeObjectAtIndex:i];
                            [self.packageIndexArray replaceObjectAtIndex:j withObject:tempArray];

#warning somthing need to confirm with wusiping.
                           [self.tableParts removeObjectAtIndex:i];
                            
                            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
                        }
                        
                    }];
                    
                    [partScrollView addSubview:itemView];
                    
                }
                [partScrollView setContentSize:CGSizeMake(count * 70, 80)];
                
                if(count==0){
                    PartsItemV *itemView = [[PartsItemV alloc] initDHVWithFram:CGRectMake(0, 0, 60, partsView.height) ordinal:1  Data:@[]  onClick:^(BOOL isSee)  {
                        
                    }];
                    
                    itemView.hidden = YES;
                    [partScrollView addSubview:itemView];
                }
                [cellView addSubview:partScrollView];
                [partsView addSubview:cellView];
                
            }
        }
        
        
        [headerView addSubview:partsView];
        
        UIView *statusView=[[UIView alloc] initWithFrame:CGRectMake(0, headerView.height-30, headerView.width, 30)];
        [statusView setBackgroundColor:[UtilCheck hexStringToColor:LineColor alpha:1]];
        CGFloat width=statusView.width/4.f;
        
        for(int i=0;i<4;i++){
            
            RZCustomLable *labTitle=[[RZCustomLable alloc] init];
            [labTitle setFont:CustomFont(14)];
            [labTitle setTextColor:[UtilCheck hexStringToColor:@"9d9fa1" alpha:1] ];
            [statusView addSubview:labTitle];
            
            [labTitle setFrame:CGRectMake(i*width, 0, width, statusView.height)];
            labTitle.text=[NSString stringWithFormat:@"  %@",[THMangerTool language:@"setting.plateName"]];
            if(i==1){
                labTitle.left-=20;
               labTitle.width+=20;
                labTitle.text=[NSString stringWithFormat:@"  %@",[THMangerTool language:@"setting.plateNO"]];
            }
            else if(i==2){
              labTitle.width-=20;
                 labTitle.left+=10;
                labTitle.text=[NSString stringWithFormat:@"  %@",[THMangerTool language:@"setting.plateCode"]];
            }
            else if(i==3){
                 labTitle.left-=10;
              labTitle.width+=20;
                labTitle.text=[NSString stringWithFormat:@"  %@",[THMangerTool language:@"setting.plateSerial"]];
            }
            else{
                labTitle.width-=20;
            }
            
            
        }
        [headerView addSubview:statusView];
    }
    
    return headerView;
}

//显示按钮
-(void)btnOpen:(RZCustomButtom*)sender{
    sender.selected=!sender.selected;
    open=sender.selected;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
 
}



#pragma mark 点击事件


/**
 点击加减按钮

 @param sender 按钮
 */
- (void)touchAddBtn:(UIButton *)sender{
    long tag = sender.tag - 2000;
    if (tag < 0) {
        NSLog(@"按钮的tag值不对");
        return;
    }
    else if (tag == 0)// +
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc]initWithCapacity:0];
        [self.packageIndexArray addObject:tempArray];
        [self.tableView reloadData];

    }
    else{// -
        
        
        NSMutableArray *currentArray = [self.packageIndexArray[tag] mutableCopy];
    
        if (currentArray.count == 0    ) {
            [self.packageIndexArray removeObjectAtIndex:tag];
            [self.tableView reloadData];
            return;
        }
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"此操作会删除当前批次，并将当前批次中的打包内容移至上一批次中，确认操作吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSMutableArray *tempArray = [[NSMutableArray alloc]initWithArray:[THMangerTool deepCopy:self.packageIndexArray[tag - 1]]];
            
            
            [tempArray addObjectsFromArray:[[NSMutableArray alloc]initWithArray:[THMangerTool deepCopy:self.packageIndexArray[tag ]]]];
            [self.packageIndexArray replaceObjectAtIndex:tag - 1  withObject:tempArray];
            [self.packageIndexArray removeObjectAtIndex:tag];
            [self.tableView reloadData];

            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        if(open){
        
         return  [self.tableArray count];
        }else{
            return 0;
        }
    }
    else{
        return [self.selectParts count];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        
        DeliveryPartsInfoTC *cell= [[DeliveryPartsInfoTC alloc] init];
        cell.data=self.tableArray[indexPath.row];
        CGFloat heigt=  [cell createStepView];
        NSLog(@"%f",heigt);
        return heigt;
 
    }
    else{
        return 45;
    }
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        
        DeliveryPartsInfoTC *cell = (DeliveryPartsInfoTC*)[tableView dequeueReusableCellWithIdentifier:@"DeliveryPartsInfoTC"];
        
        if(cell == nil)
        {
            cell = [[DeliveryPartsInfoTC alloc] init];
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
 
        cell.data=[self.tableArray objectAtIndex:indexPath.row];
       
        return cell;
  
    }
    else
    {
        DeliveryPartsTC *cell = [[DeliveryPartsTC alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"DeliveryPartsTC"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dict=self.selectParts[indexPath.row];
        cell.nameLab.text=[NSString stringWithFormat:@"  %@",[dict objectForKey:@"partsName"] ];
        cell.snLab.text=[NSString stringWithFormat:@"  %@",[dict objectForKey:@"partsSN"] ];
        cell.vsLab.text=[NSString stringWithFormat:@"  %@",[dict objectForKey:@"partsVersion"] ];
        cell.codeLab.text=[NSString stringWithFormat:@"  %@",[dict objectForKey:@"partsCode"] ];
        
        
        return cell;
    }
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
}

#pragma mark PX delegate
- (void)getselect:(NSString *)getselect mark:(int)mark row:(int)row{
    if (getselect != nil) {
        if (mark == 1000) {
            self.logisticsInfoDict = [[NSMutableDictionary alloc]initWithDictionary:self.logisCompanyArray[row]];
            [self.tableView reloadData];
        }

        else if (mark == 1002) {

            NSMutableArray *tempArray = [[NSMutableArray alloc]initWithArray:self.packageIndexArray[row]];
            [tempArray addObject:[THMangerTool deepCopy: self.currentPackingDict]];
            [self.packageIndexArray replaceObjectAtIndex:row withObject:tempArray];
            [self.tableParts addObject:[THMangerTool deepCopy: self.selectParts]];

            [self.selectParts removeAllObjects];
            [self.tableView reloadData];
            

        }

    }
}

#pragma mark 是否可以添加的判断方法



-(void)isCanAddDict:(NSDictionary *)dict{
    
    
    
    //推荐打包件，flag 为0 是表示不在推荐打包件中，-1表示在
    int flag = 0;
    
    //为0表示不在已经打包件中了，为-1表示在已经打包件中
    int flag1 = 0;
    
    //为0表示不在当前打包件中，为-1表示在
    int flag2 = 0;
    
    
    NSMutableDictionary *currentDict = [[NSMutableDictionary alloc]init];
    
    for (int i = 0 ; i < self.tableArray.count ; i ++ ) {//是否是推荐的
        NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]initWithDictionary:self.tableArray[i]];
        
        if ([self dict1:dict isBelongTodict2:tempDict]) {
            flag = -1;
            currentDict = [tempDict mutableCopy];
            break;
        }
    }
    
    if (flag == -1) {
        for (int i = 0 ; i < self.tableParts.count; i ++) {//是否已经添加过了
            NSMutableArray *tempArray = [[NSMutableArray alloc]initWithArray:self.tableParts[i]];
            for (int j = 0 ; j < tempArray.count; j ++) {
                NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]initWithDictionary:tempArray[j]];
                if ([self dict1:dict isBelongTodict2:tempDict]) {
                    flag1 = -1;
                    break;
                }
            }
        }
    }else{
        [Toolobject showTextWithMessage:@"不是推荐的板件"];
        return;
    }
    
    if (flag1 == 0) {
        for (int i = 0 ; i < self.selectParts.count ; i ++) {
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]initWithDictionary:self.selectParts[i]];
            if ([self dict1:dict isBelongTodict2:tempDict]) {
                flag2 = -1;
                break;
            }
        }

    }else {
        [Toolobject showTextWithMessage:@"该板件已经打包了"];
        return;
    }
    
    if (flag2 == 0) {
        
        if (dict.count < 4) {
            if ([dict objectForKey:@"partsSN"] == nil || [[dict objectForKey:@"partsSN"] length] <= 0   ) {
                [self.selectParts addObject:dict];//没有序列号，只加自己输入的
                [self.tableView reloadData];
            }
            else{
                [self.selectParts addObject:currentDict];//有序列号的情况下匹配所有
                [self.tableView reloadData];
            }
        }
        
    }else{
        [Toolobject showTextWithMessage:@"该板件已经打包了"];
        return;
    }
}

/**
 *  检查字典dict1是否属于dict2 （dict1中所有的键值都在dict2中有且相等，但dict2可以比dict1键值多）
 */
- (BOOL) dict1:(NSDictionary *)dict1 isBelongTodict2:(NSDictionary *)dict2{
    __block int flag = 0;
    [dict1 enumerateKeysAndObjectsUsingBlock:^(id dict1key, id dict1obj, BOOL *stop) {
        NSLog(@"dict1key = %@ and dict1obj = %@", dict1key, dict1obj);

        if (![[dict2 objectForKey:dict1key] isEqualToString:dict1obj]) {
            flag = -1;
        }
    }];
    
    if (flag < 0 ) {
        return NO;
    }else
        return YES;

}



@end
